package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.modular.system.controller.ActivityUtil.jumpAnyWhereCmd;
import cn.stylefeng.guns.modular.system.controller.dto.BackDTO;
import cn.stylefeng.guns.modular.system.controller.dto.IndentOrderTask;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.model.params.IndentOrderAuditParam;
import cn.stylefeng.guns.modular.system.model.params.IndentOrderCheckParam;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 订货单审核表控制器
 *
 * @author 小飞
 * @Date 2019-07-03 11:44:32
 */
@Controller
@RequestMapping("/indentOrderCheck")
public class IndentOrderCheckController extends BaseController {
    private String PREFIX = "/indentOrderCheck";
    @Resource
    private TaskService taskService;

    @Autowired
    private IndentOrderCheckService indentOrderCheckService;
    @Autowired
    private CheckLoggingService checkLoggingService;
    @Autowired
    private IndentOrderService indentOrderService;
    @Autowired
    private AddressRoleService addressRoleService;
    @Autowired
    private DeptService deptService;
    @Resource
    private IndentOrderAuditService indentOrderAuditService;
    @Autowired
    private UserService userService;
    @Autowired
    private DealerLevelService dealerLevelService;
    @Autowired
    private LevelService levelService;
    @Autowired
    private UserAreaRelationService userAreaRelationService;
    @Resource
    private ProcessEngine processEngine;

    /**
     * 跳转到主页面
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/indentOrderCheck.html";
    }

    /**
     * 新增页面
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/indentOrderCheck_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/indentOrderCheck_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(IndentOrderCheckParam indentOrderCheckParam) {
        this.indentOrderCheckService.add(indentOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(IndentOrderCheckParam indentOrderCheckParam) {
        this.indentOrderCheckService.update(indentOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(IndentOrderCheckParam indentOrderCheckParam) {
        this.indentOrderCheckService.delete(indentOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 小飞
     * @Date 2019-07-03
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(IndentOrderCheckParam indentOrderCheckParam) {
        IndentOrderCheck detail = this.indentOrderCheckService.getById(indentOrderCheckParam.getId());
        return ResponseData.success(detail);
    }


    @RequestMapping("/shenhe")
    @ResponseBody
    public ResponseData shenhe(IndentOrderAuditParam indentOrderAuditParam) {

        IndentOrderAudit indentOrderAudit = new IndentOrderAudit();
        BeanUtils.copyProperties(indentOrderAuditParam, indentOrderAudit);
        indentOrderAudit.setAuditTime(new Date());
        indentOrderAudit.setUserId(ShiroKit.getUserNotNull().getId());
        Task task = taskService.createTaskQuery().taskId(indentOrderAuditParam.getTaskId()).singleResult();
        indentOrderAudit.setProcessInstanceId(task.getProcessInstanceId());
        indentOrderAuditService.save(indentOrderAudit);

        //启动审核流程
        Map<String, Object> map = new HashMap<>();
        map.put("status", indentOrderAuditParam.getAuditStatus());
        taskService.complete(task.getId(), map);

        return ResponseData.success(200, "审核成功", indentOrderAudit);
    }


    /**
     * 跳转到审核页面
     *
     * @return
     */
    @RequestMapping("/shenheIndex")
    public String shenheIndex(String taskId, Long indentOrderId) {
        super.setAttr("taskId", taskId);
        super.setAttr("indentOrderId", indentOrderId);
        return PREFIX + "/indentOrderCheck_edit.html";
    }

    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(IndentOrderCheckParam indentOrderCheckParam) {
        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("pc_indent_order").taskCandidateUser(ShiroKit.getUserNotNull().getId() + "").list();
        if (tasks.size() == 0) {
            return new LayuiPageInfo();
        }

        //找出当前审核人员的区域
        List<UserAreaRelation> userAreaRelations = userAreaRelationService.getBaseMapper().selectList(new QueryWrapper<UserAreaRelation>()
        .lambda().eq(UserAreaRelation::getUserId,ShiroKit.getUserNotNull().getId()));
        if (userAreaRelations != null &&userAreaRelations.size() != 0 ){

            List<Long> areaIds = userAreaRelations.stream().map(s ->s.getAddressId()).collect(Collectors.toList());
            List<IndentOrderTask> indentOrderTasks = tasks.stream().
                    filter(task -> indentOrderService.getByProcessInstanceId(task.getProcessInstanceId()) != null)
                    .filter(task -> areaIds.contains(getAreaId(task)))
                    .map(task -> {
                IndentOrderTask indentOrderTask = new IndentOrderTask();

                BeanUtils.copyProperties(indentOrderService.getByProcessInstanceId(task.getProcessInstanceId()), indentOrderTask);
                indentOrderTask.setDealerName(userService.getById(indentOrderTask.getDealer()).getName());
                if (dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                        .lambda().eq(DealerLevel::getSysUserId, userService.getById(indentOrderTask.getDealer()).getDeptId())) != null) {
                    indentOrderTask.setDealerLevel(levelService.getById(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                            .lambda().eq(DealerLevel::getSysUserId, userService.getById(indentOrderTask.getDealer()).getDeptId())).getLevelId()).getLevelName());
                }
                indentOrderTask.setProcessInstanceId(task.getProcessInstanceId());
                indentOrderTask.setTaskId(task.getId());
                return indentOrderTask;
            }).collect(Collectors.toList());
            LayuiPageInfo result = new LayuiPageInfo();
            result.setCount(indentOrderTasks.size());
            result.setData(indentOrderTasks);
            return result;

        }else {
            return new LayuiPageInfo();
        }

    }

    /**
     * 获取当前订单的区域id
     * @param task
     * @return
     */
    public Long getAreaId(Task task){

        if (ToolUtil.isNotEmpty(task)){
            IndentOrder indentOrder = indentOrderService.getOne(new QueryWrapper<IndentOrder>()
            .lambda().eq(IndentOrder::getProcessInstanceId,task.getProcessInstanceId()));
            if (ToolUtil.isNotEmpty(indentOrder)){
                User user = userService.getById(indentOrder.getDealer());
                if (ToolUtil.isNotEmpty(user)){
                    Dept dept = deptService.getById(user.getDeptId());
                    if (ToolUtil.isNotEmpty(dept)){
                        DealerLevel dealerLevel = dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                        .lambda().eq(DealerLevel::getSysUserId,dept.getDeptId()));
                        if (ToolUtil.isNotEmpty(dealerLevel)){
                            return  dealerLevel.getAreaId();
                        }
                    }
                }
            }
        }
        return  null;
    }

   /*-------------------------------------退回start----------------------------------------------------*/
    /**
     * 退回接口
     * @param backDTO
     * @return
     */
    @ResponseBody
    @RequestMapping("/back")
    public ResponseData back(BackDTO backDTO){

        //插入到审核记录表
        IndentOrderAudit indentOrderAudit = new IndentOrderAudit();
        BeanUtils.copyProperties(backDTO,indentOrderAudit);
        indentOrderAudit.setUserId(ShiroKit.getUserNotNull().getId());
        Task task = taskService.createTaskQuery().taskId(backDTO.getTaskId()).singleResult();
        indentOrderAudit.setProcessInstanceId(task.getProcessInstanceId());


        processEngine.getManagementService().executeCommand(new jumpAnyWhereCmd(backDTO.getTaskId(),backDTO.getTargetNodeId(),backDTO.getComment()));
        return ResponseData.success();
    }
    /**
     * 退回页面
     * @param taskId
     * @return
     */
    @RequestMapping("/backIndex")
    public String backIndex(String taskId,Long id){
        super.setAttr("taskId",taskId);
        return PREFIX + "/return.html";
    }
   /*---------------------------------退回end---------------------------------------------------------*/



    @RequestMapping("/orderDetail")
    public String indentOrderDetail(Model model, Long id, String taskId) {
        //经销商登录名
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        model.addAttribute("username", shiroUser.getName());
        //部门
        String deptName = deptService.getById(shiroUser.getDeptId()).getSimpleName();
        model.addAttribute("deptName", deptName);
        IndentOrder indentOrder = indentOrderService.getById(id);
        String ids = indentOrder.getPurchaseId();
        model.addAttribute("dealer",indentOrder.getDealer());
        model.addAttribute("ids", ids);
        model.addAttribute("id", id);
        model.addAttribute("taskId", taskId);
        return PREFIX + "/indentCheck.html";
    }


}






